from flask import Blueprint, jsonify, request, current_app
from ..models.airport import Airport
from ..models.oil_tank import OilTank
from .. import db
from sqlalchemy import func
import math

bp = Blueprint('oil_supply', __name__, url_prefix='/api/oil-supply')

@bp.route('/facilities', methods=['GET'])
def get_facilities():
    """获取所有油料设施"""
    region = request.args.get('region', 'all')
    
    try:
        query = db.session.query(
            OilTank.id,
            OilTank.name,
            OilTank.type,
            OilTank.area,
            OilTank.location,
            Airport.region,
            Airport.latitude,
            Airport.longitude
        ).join(Airport)
            
        if region != 'all':
            query = query.filter(Airport.region == region)
    
        facilities = query.all()
        
        return jsonify([{
            'id': f.id,
            'name': f.name,
            'type': f.type,
            'area': f.area,
            'location': f.location,
            'region': f.region,
            'latitude': f.latitude,
            'longitude': f.longitude
        } for f in facilities])
        
    except Exception as e:
        current_app.logger.error(f'获取设施数据失败: {str(e)}')
        return jsonify({'error': str(e)}), 500

@bp.route('/network', methods=['GET'])
def get_network_data():
    """获取油料供应网络数据"""
    region = request.args.get('region', 'all')
    
    try:
        # 获取所有机场油库数据
        query = db.session.query(
            OilTank.id,
            OilTank.name,
            OilTank.type,
            OilTank.area,
            OilTank.location,
            Airport.region,
            Airport.latitude,
            Airport.longitude
        ).join(Airport)
        
        # 如果指定了区域，添加过滤条件
        if region != 'all':
            query = query.filter(Airport.region == region)
            
        oil_tanks = query.all()
        
        # 转换数据为前端需要的格式
        nodes = []
        for oil_tank in oil_tanks:
            nodes.append({
                'id': oil_tank.id,
                'name': oil_tank.name,
                'facility_type': 'airport',  # 机场油库类型
                'region': oil_tank.region,
                'value': oil_tank.area,  # 使用面积作为容量值
                'latitude': oil_tank.latitude,
                'longitude': oil_tank.longitude,
                'location': oil_tank.location,  # 添加位置信息
                'category': 3  # 机场油库的分类编号
            })
        
        # 定义分类
        categories = [
            {'name': '原油进口设施'},
            {'name': '炼油厂'},
            {'name': '区域存储油库'},
            {'name': '机场油库'}
        ]
        
        return jsonify({
            'nodes': nodes,
            'links': [],  # 暂时不处理连接关系
            'categories': categories
        })
            
    except Exception as e:
        current_app.logger.error(f'获取网络数据失败: {str(e)}')
        return jsonify({'error': str(e)}), 500

@bp.route('/trace/<int:facility_id>', methods=['GET'])
def trace_supply_chain(facility_id):
    """追踪设施供应链"""
    try:
        # 获取设施信息
        facility = db.session.query(
            OilTank.id,
            OilTank.name,
            OilTank.type,
            OilTank.area,
            OilTank.location,
            Airport.region,
            Airport.latitude,
            Airport.longitude
        ).join(Airport).filter(OilTank.id == facility_id).first()
        
        if not facility:
            return jsonify({'error': 'Facility not found'}), 404
            
        facility_dict = {
            'id': facility.id,
            'name': facility.name,
            'region': facility.region,
            'latitude': facility.latitude,
            'longitude': facility.longitude,
            'value': facility.area,
            'facility_type': 'storage',
            'location': facility.location
        }
        
        # 获取相关设施（同一区域的其他设施）
        related_facilities = db.session.query(
            OilTank.id,
            OilTank.name,
            OilTank.type,
            OilTank.area,
            OilTank.location,
            Airport.region,
            Airport.latitude,
            Airport.longitude
        ).join(Airport).filter(
            Airport.region == facility.region,
            OilTank.id != facility_id
        ).all()
        
        related_dicts = []
        for related in related_facilities:
            related_dicts.append({
                'id': related.id,
                'name': related.name,
                'region': related.region,
                'latitude': related.latitude,
                'longitude': related.longitude,
                'value': related.area,
                'facility_type': 'storage',
                'location': related.location
            })
        
        # 构建供应链连接
        links = []
        for related in related_dicts:
            links.append({
                'source': facility_dict['id'],
                'target': related['id'],
                'transportation': 'pipeline'
            })
        
        return jsonify({
            'facility': facility_dict,
            'nodes': [facility_dict] + related_dicts,
            'links': links
        })
        
    except Exception as e:
        current_app.logger.error(f'追踪供应链失败: {str(e)}')
        return jsonify({'error': str(e)}), 500

def calculate_distance(source, target):
    """计算两个设施之间的距离（公里）"""
    # 地球半径（公里）
    R = 6371.0
    
    # 转换为弧度
    lat1 = math.radians(source.latitude)
    lon1 = math.radians(source.longitude)
    lat2 = math.radians(target.latitude)
    lon2 = math.radians(target.longitude)
    
    # 经纬度差
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    
    # Haversine公式
    a = math.sin(dlat / 2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2)**2
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    distance = R * c
    
    return round(distance, 2)

def get_categories():
    """获取油料设施分类"""
    return [
        {'name': '原油进口设施'},
        {'name': '炼油厂'},
        {'name': '区域存储油库'},
        {'name': '机场油库'}
    ] 